package com.zzy.common.util;


import com.zzy.common.entity.db.AdminDaoEntity;
import com.zzy.common.exception.BotException;
import com.zzy.common.finalfied.ResultCode;
import com.zzy.common.finalfied.ResultMessage;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

/**
 * @author zhuZhaoYang
 * @date 2021/7/12 9:54
 */
public class LoginUtils {

    public static String md5(String password, String salt) {
        return new Md5Hash(password, salt).toHex();
    }

    private static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public static AdminDaoEntity getLoginUser() {
        if (SecurityUtils.getSubject() == null || SecurityUtils.getSubject().getPrincipal() == null) {
            throw new UnauthenticatedException();
        }
        return (AdminDaoEntity) SecurityUtils.getSubject().getPrincipal();
    }


    public static void setSessionAttribute(Object key, Object value) {
        if (key == null || value == null) {
            return;
        }
        getSession().setAttribute(key, value);
    }

    public static void checkLogin() {
        getLoginUser();
    }


    public static void logout() {
        SecurityUtils.getSubject().logout();
    }

    private static Object getSessionAttribute(Object object) {
        if (getSession() == null) {
            return null;
        }
        return getSession().getAttribute(object);
    }

    public static void login(String userName, String password) {
        SecurityUtils.getSubject().login(new UsernamePasswordToken(userName, password));
    }

    public static String getKaptcha(String key) {
        Object kaptcha = getSessionAttribute(key);
        if (kaptcha == null) {
            throw new BotException(ResultCode.PARAMETER_ERROR, ResultMessage.VERIFICATION_NOT_LONGER_USE);
        }
        getSession().removeAttribute(key);
        return kaptcha.toString();
    }

}
